﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using BCommon;
using DN_CtrDisplay;
using GTS;
using gts;

namespace GtsMotion
{
    public partial class MotionForm : Form
    {
        private GTS800 MyGts;


        public MotionForm()
        {
            InitializeComponent();
            IniMotion();
            IniGridIO();
            CtrDisplay.dataGridView_Resize(dgv_IO, 0);
            CtrDisplay.dataGridView_Resize(dgv_MotionPT,80);


            //加载Form上Button控件的一些方法
            foreach (var control in this.Controls)
            {
                if(control is Button)
                {
                    Button b = (Button)control;
                    b.MouseEnter += CtrDisplay.button_MouseEnter;
                    b.MouseLeave += CtrDisplay.button_MouseLeave;
                }
            }
        }

        /// <summary>
        /// 初始化电机
        /// </summary>
        public void IniMotion()
        {
            MyGts = new GTS800();
            if (MyGts.Init())
            {

                MyGts.SetScale(1, (10000 * 1.0) / (10.0 * 1.0));//10000细分5mm螺距
                MyGts.SetScale(2, (10000 * 1.0) / (10.0 * 1.0));
                MyGts.SetScale(3, (10000 * 1.0) / (10.0 * 1.0));
                // MyGts.SetScale(4, (10000 * 1.0) / (360.0 * 1.0));

            }

            SaveorReadPTParams("GTS800.ini", false); //读取配置文件
            Homeback();//回零点
            tmr_Position.Start();
            tmr_IO.Start();

        }

        /// <summary>
        /// 读取或写入配置文件
        /// </summary>
        /// <param name="path">文件名</param>
        /// <param name="isSave">真为写入，假为读取</param>
        private void SaveorReadPTParams(string path, bool isSave)
        {
            Bini.SetPath(path);
            SaveParam(isSave);
        }

        public const int ParamNum = 16;
        private string[] strNamemes = new string[ParamNum];
        private double[] ParamAxis1 = new double[ParamNum];
        private double[] ParamAxis2 = new double[ParamNum];
        private double[] ParamAxis3 = new double[ParamNum];
        private double[] ParamAxis4 = new double[ParamNum];
        private double[] ParamVel = new double[ParamNum];
        private double[] ParamAcc = new double[ParamNum];
        private string[] m_VelAcc = new string[2];
        /// <summary>
        /// 读写配置文件
        /// </summary>
        /// <param name="sts"></param>
        private void SaveParam(bool sts)
        {
            try
            {
                Bini.SetPath("GTS800.ini");
                if (sts)  //sts=true，保存参数
                {
                    for (int i = 0; i < ParamNum; i++)
                    {
                        strNamemes[i] = dgv_MotionPT.Rows[i].Cells[0].Value.ToString();
                        ParamVel[i] = double.Parse(dgv_MotionPT.Rows[i].Cells[1].Value.ToString());
                        ParamAcc[i] = double.Parse(dgv_MotionPT.Rows[i].Cells[2].Value.ToString());
                        ParamAxis1[i] = double.Parse(dgv_MotionPT.Rows[i].Cells[3].Value.ToString());
                        ParamAxis2[i] = double.Parse(dgv_MotionPT.Rows[i].Cells[4].Value.ToString());
                        ParamAxis3[i] = double.Parse(dgv_MotionPT.Rows[i].Cells[5].Value.ToString());
                        double d_temp = double.Parse(dgv_MotionPT.Rows[i].Cells[6].Value.ToString());
                        ParamAxis4[i] = double.Parse(dgv_MotionPT.Rows[i].Cells[6].Value.ToString());
                        Bini.SetValue("MesName", "Name" + i.ToString(), strNamemes[i]);
                        Bini.SetValue("Motion", "Vel" + i.ToString(), ParamVel[i].ToString());
                        Bini.SetValue("Motion", "Acc" + i.ToString(), ParamAcc[i].ToString());
                        Bini.SetValue("Motion", "X" + i.ToString(), ParamAxis1[i].ToString());
                        Bini.SetValue("Motion", "Y" + i.ToString(), ParamAxis2[i].ToString());
                        Bini.SetValue("Motion", "Z" + i.ToString(), ParamAxis3[i].ToString());
                        Bini.SetValue("Motion", "U" + i.ToString(), ParamAxis4[i].ToString());

                    }
                    m_VelAcc[0] = tbx_velocity.Text;
                    m_VelAcc[1] = tbx_acceleration.Text;
                    Bini.SetValue("Motion", "VelTemp", m_VelAcc[0]);
                    Bini.SetValue("Motion", "AccTemp", m_VelAcc[1]);


                }
                else  //sts=false，从配置文件中读取
                {

                    for (int i = 0; i < ParamNum; i++)
                    {
                        strNamemes[i] = Bini.GetValue("MesName", "Name" + i.ToString());             //测量的名字
                        ParamVel[i] = double.Parse(Bini.GetValue("Motion", "Vel" + i.ToString()));
                        ParamAcc[i] = double.Parse(Bini.GetValue("Motion", "Acc" + i.ToString()));
                        ParamAxis1[i] = double.Parse(Bini.GetValue("Motion", "X" + i.ToString()));
                        ParamAxis2[i] = double.Parse(Bini.GetValue("Motion", "Y" + i.ToString()));
                        ParamAxis3[i] = double.Parse(Bini.GetValue("Motion", "Z" + i.ToString()));
                        ParamAxis4[i] = double.Parse(Bini.GetValue("Motion", "U" + i.ToString()));

                        dgv_MotionPT.Rows.Add(strNamemes[i]);

                        dgv_MotionPT.Rows[i].Cells[1].Value = ParamVel[i].ToString();
                        dgv_MotionPT.Rows[i].Cells[2].Value = ParamAcc[i].ToString();
                        dgv_MotionPT.Rows[i].Cells[3].Value = ParamAxis1[i].ToString();
                        dgv_MotionPT.Rows[i].Cells[4].Value = ParamAxis2[i].ToString();
                        dgv_MotionPT.Rows[i].Cells[5].Value = ParamAxis3[i].ToString();
                        dgv_MotionPT.Rows[i].Cells[6].Value = ParamAxis4[i].ToString();
                    }
                    m_VelAcc[0] = (Bini.GetValue("Motion", "VelTemp"));
                    tbx_velocity.Text = m_VelAcc[0];
                    m_VelAcc[1] = (Bini.GetValue("Motion", "AccTemp"));
                    tbx_acceleration.Text = m_VelAcc[1];
                }
            }
            catch (Exception)
            {
                MessageBox.Show("只能设置成数字！");
            }


        }

        /// <summary>
        /// 回原点
        /// </summary>
        public void Homeback()
        {
            //SetOutput(4, false);
            // SetOutput(4, true);
            //SetOutput(6, false);
            //SetOutput(7, false);
            //AirUp2(false);
            AirUp1(false);

            //MyGts.H_LimitOn(2, 1);
            //MyGts.H_LimitOn(4, 1);

            MyGts.HomeByLimit(1, 1, 5, 0.5);//负限位为1，正限为-1
            MyGts.HomeByLimit(2, 1, 5, 0.5);
            MyGts.HomeByLimit(3, 1, 2, 0.1);


            //MyGts.H_LimitOff(2, 1);
            //MyGts.H_LimitOff(4, 1);

            try
            {

                //MyGts.Move(1, ParamAxis1[0], ParamVel[0], ParamAcc[0]);
                //MyGts.Move(2, ParamAxis2[0], 100, ParamAcc[0]);
                //MyGts.Move(3, ParamAxis3[0], ParamVel[0], ParamAcc[0]);

                //MyGts.WaitStop(1);
                //MyGts.WaitStop(2);
                //MyGts.WaitStop(3);


            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// 使轴停止
        /// </summary>
        /// <param name="nAxis"></param>
        /// <param name="bSmooth"></param>
        public void stop(short nAxis, bool bSmooth)
        {
            MyGts.Stop(nAxis, bSmooth);
        }

        /// <summary>
        /// 获取规划位置
        /// </summary>
        /// <param name="axis"></param>
        /// <returns></returns>
        public double gtpos(short axis)
        {
            return MyGts.GetMotoPos(axis, true);
        }

        /// <summary>
        /// 运动模式
        /// </summary>
        /// <param name="numX"></param>
        /// <param name="xsts"></param>
        /// <param name="ysts"></param>
        /// <param name="zsts"></param>
        public void MoveModle(int numX, bool xsts, bool ysts, bool zsts)
        {
            try
            {
                if (xsts) MyGts.Move(1, ParamAxis1[numX], ParamVel[numX], ParamAcc[numX]);
                if (ysts) MyGts.Move(2, ParamAxis2[numX], ParamVel[numX], ParamAcc[numX]);
                if (zsts) MyGts.Move(3, ParamAxis3[numX], ParamVel[numX], ParamAcc[numX]);

                MyGts.WaitStop(1);
                MyGts.WaitStop(2);
                MyGts.WaitStop(3);
            }

            catch (Exception)
            {
            }
        }

        public void MoveModle2(int numX, bool xsts, bool ysts, bool zsts)
        {
            try
            {
                if (xsts) MyGts.Move(1, ParamAxis1[numX], ParamVel[numX], ParamAcc[numX]);
                if (ysts) MyGts.Move(2, ParamAxis2[numX], ParamVel[numX], ParamAcc[numX]);
                if (zsts) MyGts.Move(3, ParamAxis3[numX], ParamVel[numX], ParamAcc[numX]);

            }
            catch (Exception)
            {
            }

        }

        public void MoveModle3(int numX, bool xsts, bool ysts, double Uvel)
        {
            try
            {

                if (xsts) MyGts.Move(1, ParamAxis1[numX], ParamVel[numX], ParamAcc[numX]);
                if (ysts)
                {
                    MyGts.Move(2, ParamAxis2[numX], 3 * Uvel, ParamAcc[numX]);

                }
                MyGts.WaitStop(1);
                MyGts.WaitStop(2);

            }
            catch (Exception)
            {
            }
        }

        public void MoveModle4(int numX, bool xsts, bool ysts, double Uvel)
        {
            try
            {

                if (xsts) MyGts.Move(3, ParamAxis3[numX], ParamVel[numX], ParamAcc[numX]);
                if (ysts)
                {

                    MyGts.Move(4, ParamAxis4[numX], 3 * Uvel, ParamAcc[numX]);


                }
                MyGts.WaitStop(3);
                MyGts.WaitStop(4);

            }
            catch (Exception)
            {
            }
        }

        public bool IsInPut(short nBit)
        {
            int i = 0;
            while (true)
            {
                i++;
                if (MyGts.GetInput(nBit)) return true;
                Thread.Sleep(5);
                if (i > 200) return false;
            }
        }

        public void LimitOff(short nAxis, short LimitType)
        {
            MyGts.H_LimitOff(nAxis, LimitType);
        }

        public void LimitOn(short nAxis, short LimitType)
        {
            MyGts.H_LimitOn(nAxis, LimitType);
        }

        public void SetOutput(int nBit, bool bOn)
        {
            MyGts.SetOutput(nBit, bOn);
        }

        public bool GetInput(short nBit)
        {
            return MyGts.GetInput(nBit);
        }

        private void btn_IniMotion_Click(object sender, EventArgs e)
        {
            IniMotion();
        }


        private void btn_Home_Click(object sender, EventArgs e)
        {
            Homeback();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
       
        }

        private void button5_Click(object sender, EventArgs e)
        {
        }

        private void tmr_Position_Tick(object sender, EventArgs e)
        {
            double x, y, z, u;
            x = MyGts.GetMotoPos(1, true);//X规划位置
            y = MyGts.GetMotoPos(2, false);//Y编码器位置
            z = MyGts.GetMotoPos(3, false); //Z编码器位置


            CtrDisplay.ShowText(lbl_Position, "X:" + x.ToString("F3") + ",----Y:" + y.ToString("F3") +
                "----Z:" + z.ToString("F3"));


        }


        private void btn_Axis_MouseDown(object sender, MouseEventArgs e)
        {

            string[] num = ((Button)sender).Tag.ToString().Split(',');//num[1]符号表示方向

            try
            {
                if (tbx_Step.Text == "0")
                {
                    MyGts.Move(int.Parse(num[0]), int.Parse(num[1]), double.Parse(m_VelAcc[0]), double.Parse(m_VelAcc[1]));
                }
                else
                {
                    double xx = MyGts.GetCmdPos(short.Parse(num[0]));
                    if (int.Parse(num[1]) >= 0)
                    {
                        MyGts.Move(int.Parse(num[0]), xx + double.Parse(tbx_Step.Text), double.Parse(m_VelAcc[0]), double.Parse(m_VelAcc[1]));
                    }
                    else
                    {
                        MyGts.Move(int.Parse(num[0]), xx - double.Parse(tbx_Step.Text), double.Parse(m_VelAcc[0]), double.Parse(m_VelAcc[1]));
                    }
                }
            }
            catch
            {
            }


        }
        private void btn_Axis_MouseUp(object sender, MouseEventArgs e)
        {
            string[] num = ((Button)sender).Tag.ToString().Split(',');

            if (tbx_Step.Text == "0")
            {
                MyGts.Stop(short.Parse(num[0]), true);
            }

        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Visible = false;
        }

        private void btn_Set_Click(object sender, EventArgs e)
        {
            SaveParam(true);
        }

        private void tabVelAcc_TextChanged(object sender, EventArgs e)
        {
            m_VelAcc[0] = tbx_velocity.Text;
            m_VelAcc[1] = tbx_acceleration.Text;
        }

        private void btn_MoveXY_Click(object sender, EventArgs e)
        {
            int IndexGridRow = dgv_MotionPT.CurrentRow.Index;
            try
            {

                MyGts.Move(1, ParamAxis1[IndexGridRow], ParamVel[IndexGridRow], ParamAcc[IndexGridRow]);
                MyGts.Move(2, ParamAxis2[IndexGridRow], ParamVel[IndexGridRow], ParamAcc[IndexGridRow]);
             //MyGts.Move(3, ParamAxis3[IndexGridRow], ParamVel[IndexGridRow]/3, ParamAcc[IndexGridRow]/3);


                MyGts.WaitStop(1);
                MyGts.WaitStop(2);
             //MyGts.WaitStop(3);

            }
            catch (Exception)
            {
            }
        }


        public void SetOutPut(int nBit, bool bOn)
        {
            MyGts.SetOutput(nBit, bOn);
        }

        public bool WaitStop(short nAxis, uint nCard = 0)
        {
            return MyGts.WaitStop(nAxis);

        }
        public bool Stop(short nAxis, uint nCard = 0)
        {
            return MyGts.Stop(nAxis, true);
        }

        private void btn_MoveZ_Click(object sender, EventArgs e)
        {
            int IndexGridRow = dgv_MotionPT.CurrentRow.Index;
            try
            {

                MyGts.Move(3, ParamAxis3[IndexGridRow], ParamVel[IndexGridRow], ParamAcc[IndexGridRow]);
                //              MyGts.Move(4, ParamAxis4[IndexGridRow], ParamVel[IndexGridRow], ParamAcc[IndexGridRow]);
                MyGts.WaitStop(3);
                //              MyGts.WaitStop(4);
            }
            catch (Exception)
            {
            }
        }

        public bool AirUp1(bool sts)
        {
            SetOutput(4, sts);
            SetOutput(5, sts);
            if (sts)
            {
                if (!IsInPut(5)) return false;
                if (!IsInPut(7)) return false;
            }
            else
            {
                if (!IsInPut(4)) return false;
                if (!IsInPut(6)) return false;
            }
            System.Threading.Thread.Sleep(50);
            return true;
        }
        public bool AirUp2(bool sts)
        {
            SetOutput(6, sts);
            SetOutput(7, sts);
            if (sts)
            {
                if (!IsInPut(9)) return false;
                if (!IsInPut(11)) return false;
            }
            else
            {
                if (!IsInPut(8)) return false;
                if (!IsInPut(10)) return false;
            }
            System.Threading.Thread.Sleep(20);

            return true;
        }

        private void tmr_IO_Tick(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < 8; i++)
                {
                    for (int j = 0; j < 2; j++)
                    {
                        bool sts = MyGts.GetOutput((short)(i + j * 8));
                        bool sts2 = MyGts.GetInput((short)(i + j * 8));
                        if (sts)
                        {

                            dgv_IO.Rows[i].Cells[j].Style.BackColor = Color.Red;
                        }
                        else
                        {
                            dgv_IO.Rows[i].Cells[j].Style.BackColor = Color.Green;

                        }
                        if (sts2)
                        {
                            dgv_IO.Rows[i].Cells[j + 2].Style.BackColor = Color.Red;
                        }
                        else
                        {
                            dgv_IO.Rows[i].Cells[j + 2].Style.BackColor = Color.Green;

                        }
                    }
                }
            }
            catch(Exception ex)
            {

            }



        }
        private void IniGridIO()
        {
            for (int i = 0; i < 8; i++)
            {
                dgv_IO.Rows.Add(i.ToString());
                dgv_IO.Rows[i].Cells[1].Value = (i + 8).ToString();
                dgv_IO.Rows[i].Cells[2].Value = i.ToString();
                dgv_IO.Rows[i].Cells[3].Value = (i + 8).ToString();
            }
            dgv_IO.ClearSelection();
        }
        private void IniGridIO_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex > 2) return;
                dgv_IO.ClearSelection();

                bool sts = MyGts.GetOutput((short)(e.RowIndex + e.ColumnIndex * 2));
                MyGts.SetOutput(e.RowIndex + e.ColumnIndex * 8, !sts);
                if (sts)
                {
                    dgv_IO.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red;
                }
                else
                {
                    dgv_IO.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Green;

                }
            }
            catch
            {

            }

        }



        private void btn_GetPos_Click(object sender, EventArgs e)
        {
            int IndexGridRow = dgv_MotionPT.CurrentRow.Index;

            dgv_MotionPT.Rows[IndexGridRow].Cells[3].Value = MyGts.GetMotoPos(1, true);
            dgv_MotionPT.Rows[IndexGridRow].Cells[4].Value = MyGts.GetMotoPos(2, false);
            dgv_MotionPT.Rows[IndexGridRow].Cells[5].Value = MyGts.GetMotoPos(3, false);
            //dgv_MotionPT.Rows[IndexGridRow].Cells[6].Value = ;

        }

        private void lbl_Position_Click(object sender, EventArgs e)
        {

        }
    }
}
